import { ts } from 'qvog-dsl';
import {
  native,
  HomeCheckHint
} from 'qvog-dsl';

const SEVERITY = 2;
const DOC_PATH = 'docs/ssrf.md';
const DESCRIPTION = 'Server-Side Request Forgery (SSRF) occurs when an application makes HTTP requests based on user input without proper validation. This may allow attackers to access internal services or protected resources.';

export default native<HomeCheckHint>()()
  .match((node): node is ts.CallExpression => ts.isCallExpression(node))
  .when((node: ts.CallExpression) => {
    const callExpr = node.expression;

    // fetch、axios、http.get/http.request、https.get/https.request
    const isSSRFRelatedMethod = (
      ts.isIdentifier(callExpr) &&
      ['fetch', 'axios'].includes(callExpr.escapedText.toString())
    ) || (
        ts.isPropertyAccessExpression(callExpr) &&
        ['http', 'https'].includes(callExpr.expression.getText()) &&
        ['get', 'request'].includes(callExpr.name.getText())
      );

    if (!isSSRFRelatedMethod) { return false };

    const firstArg = node.arguments[0];
    if (!firstArg) { return false };

    const argText = firstArg.getText().toLowerCase();
    const suspiciousSources = ['req.body', 'req.query', 'request.body', 'params', 'input', 'form'];

    return suspiciousSources.some(src => argText.includes(src));
  })
  .report({
    severity: SEVERITY,
    description: DESCRIPTION,
    docPath: DOC_PATH
  });
